import Toast from "../../../miniprogram_npm/@vant/weapp/toast/toast";
import Dialog from "../../../miniprogram_npm/@vant/weapp/dialog/dialog";
const app = getApp()
import {
  ajaxGetOrderRefundAuditList,
  ajaxOperationRefundAudit
} from '../../../api/order'

let isLoading = false;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    //自定义导航高度
    customNavHeight: app.globalData.customNavInfo.navHeight,
    baseURL: app.globalData.config.baseURL,
    // tab active
    active: 0,
    list: [],
    // 分页
    pagingOptions: {
      //分页页码
      pageNo: 1,
      //分页每页条数
      pageSize: 10,
      //下拉状态控制
      refreshState: 0,
      //上拉状态控制
      pushState: 0,
    },
    // 全选
    allChecked: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.refresh(true);
  },
  // tab change
  tabChange(e) {
    this.setData({
      allChecked: false,
      active: e.detail.index || 0
    })
    this.refresh(true);
  },
  //获取数据列表
  getList() {
    return new Promise((resolve, reject) => {
      let {
        pageNo,
        pageSize
      } = this.data.pagingOptions;
      ajaxGetOrderRefundAuditList({
        pageNo,
        pageSize,
        // auditStatus 待审核0 已处理1
        auditStatus: this.data.active
      }).then((resp) => {
        let list = (resp.data || []).map(item => {
          item.productInfoList = item.productInfoList || [];
          item.checked = false;
          return item;
        })
        resolve(list);
      }).catch((err) => {
        Toast(err.msg || '错误')
        resolve([]);
      })
    })
  },
  //下拉刷新
  refresh(showLoading) {
    if (isLoading) {
      return;
    }
    isLoading = true;
    if (showLoading) {
      //loading
      Toast.loading({
        message: '正在加载',
        forbidClick: true,
        duration: 0
      });
    }
    this.setData({
      allChecked: false,
      'pagingOptions.pageNo': 1
    }, () => {
      //请求数据第一页数据
      this.getList().then((list) => {
        this.setData({
          list: list.length ? list : []
        }, async () => {
          this.setData({
            'pagingOptions.refreshState': 1,
            'pagingOptions.pushState': list.length >= this.data.pagingOptions.pageSize ? 2 : 3
          })
          await app.myNextTick()
          Toast.clear();
          isLoading = false;
        })
      }).catch(async (err) => {
        this.setData({
          'pagingOptions.refreshState': 1
        })
        isLoading = false;
        await app.myNextTick()
        Toast.clear();
        Toast('加载失败');
      })
    })
  },
  //上拉刷新
  toload(e) {
    this.setData({
      'pagingOptions.pageNo': this.data.pagingOptions.pageNo + 1
    }, () => {
      //请求数据第一页数据
      this.getList().then((list) => {
        this.data.list.push(...(list ? list : []));
        this.setData({
          list: this.data.list,
          'pagingOptions.pushState': list.length >= this.data.pagingOptions.pageSize ? 2 : 3
        })
      }).catch((err) => {
        this.setData({
          'pagingOptions.pushState': 2
        })
      })
    })
  },
  // 订单详情
  goOrderDetails(e) {
    let {
      index
    } = e.currentTarget.dataset,
      item = this.data.list[index],
      orderId = item.orderId;
    app.commonNavigateTo(`/pages/order/orderDetails/index?orderId=${orderId}&isRefundAudit=${true}`)
  },
  nullEvent() {},
  // 订单复选框
  onChange({
    currentTarget: {
      dataset: {
        index
      }
    }
  }) {
    this.setData({
      [`list[${index}].checked`]: !this.data.list[index].checked
    })
  },
  // 全选
  allChange(e) {
    let updateObj = {};
    this.data.list.forEach((item, index) => {
      updateObj[`list[${index}].checked`] = e.detail;
    })
    this.setData({
      allChecked: e.detail,
      ...updateObj
    })
  },
  // 获取选中订单
  getCheckedOrder() {
    let ids = [];
    this.data.list.forEach(item => {
      if (item.checked) {
        ids.push(item.auditId)
      }
    })
    return ids;
  },
  // 提交审核
  async submit(e) {
    let {
      state
    } = e.currentTarget.dataset;
    let ids = this.getCheckedOrder();
    if (!ids.length) {
      Toast('至少选择一笔订单')
      return
    }
    if (state == 1) {
      try {
        await Dialog.confirm({
          message: `确定同意退款申请吗？`,
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          confirmButtonColor: "#e61211",
          zIndex: 120,
        })
      } catch (error) {
        return;
      }
    }
    try {
      Toast.loading({
        message: '正在处理',
        forbidClick: true,
        duration: 0
      });
      await ajaxOperationRefundAudit({
        auditStatus: state,
        auditIds: ids
      })

      // // 过滤掉已处理的订单
      // let newList = this.data.list.filter(item => {
      //   return ids.indexOf(item.auditId) == -1;
      // })
      // this.setData({
      //   list: newList
      // })
      // // 数据少于每页条数的一半加载一页
      // if (newList < this.data.pagingOptions.pageSize / 2) {
      //   this.toload();
      // }

      // 刷新订单
      this.refresh(true)
      await app.myNextTick()
      Toast.clear();
      Toast({
        type: 'success',
        forbidClick: true,
        message: '操作成功',
        duration: 1000,
        onClose: () => {}
      })
    } catch (err) {
      await app.myNextTick()
      Toast.clear();
      Toast(err.msg || '操作失败');
    }
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  }
})